package com.king.minepda;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.shunhao.base.BaseWebView;
import com.shunhao.model.EventCenter;
import com.shunhao.mvp.BaseMvpActivity;
import com.shunhao.mvp.BasePresenter;
import com.shunhao.utils.ImmersionBarUtils;
import com.shunhao.utils.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;

/**
 * @author KangGuiYang
 * 邮箱        kangguiyang2@gmail.com
 * 分辨率 1280x800
 * compile 'com.github.lzyzsd:jsbridge:1.0.4' 后面可自定义
 */
public class WebShellActivity extends BaseMvpActivity {

    private static final String TAG = WebShellActivity.class.getSimpleName();
    private static final String BUNDLE_KEY_URL = "URL";
    private static final int MAX_PROGRESS = 100;
    private static final int REQUEST_CODE_CHOOSE = 1;

    @BindView(R.id.web_ali)
    BaseWebView mWebView;

    @BindView(R.id.actAgreementPb)
    ProgressBar mProgressBar;

    @BindView(R.id.tv_long_click)
    TextView mTvLongClick;

    private ValueCallback<Uri[]> mFilePathCallBack;

    private String mCurrentLoadUrl = "http://conf.ruihu.work";
//    private String mCurrentLoadUrl = "http://192.168.2.200";
//    private String mCurrentLoadUrl = "http://10.36.20.32";

    public static void startWebActivity(Context context, String url) {
        Intent intent = new Intent(context, WebShellActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_KEY_URL, url);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected int getContentViewLayoutId() {
        return R.layout.activity_web;
    }


    @Override
    protected void initViews() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        ImmersionBarUtils.initColorBaseBar(this, R.color.color_base);
        // 初始化webView相关参数
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setDownloadListener(new MyWebViewDownLoadListener());

        // 确保跳转到另一个网页时仍然在当前 WebView 中显示而不是调用浏览器打开
        mWebView.setWebChromeClient(new MyChromeClient());
        mWebView.setFocusable(true);
        mWebView.setFocusableInTouchMode(true);
        mWebView.requestFocusFromTouch();
        // 清除缓存
        mWebView.clearCache(true);

        // 测试用
        mTvLongClick.setOnLongClickListener(v -> {
            readyGoThenKill(TestEnterPageActivity.class);
            return false;
        });
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String mLoadUrl = bundle.getString(BUNDLE_KEY_URL);
            if (!ObjectUtils.isEmpty(mLoadUrl)) {
                mCurrentLoadUrl = mLoadUrl;
            }
        }
        if (!ObjectUtils.isEmpty(mCurrentLoadUrl)) {
            mWebView.loadUrl(mCurrentLoadUrl);
        }
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
    }


    private class MyChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView webView, int i) {
            super.onProgressChanged(webView, i);
            if (i >= MAX_PROGRESS) {
                mProgressBar.setVisibility(View.GONE);
            } else {
                if (mProgressBar.getVisibility() == View.GONE) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
                mProgressBar.setProgress(i);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            mFilePathCallBack = filePathCallback;
            intoAlbum();
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        /**
         * 后面看 是否需要JS弹框
         *
         * @param view    view
         * @param url     url
         * @param message message
         * @param result  result
         * @return
         */
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }


    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    }


    public class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            try {
                if (url.startsWith(getString(R.string.http)) || url.startsWith(getString(R.string.https))) {
                    view.loadUrl(url);
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            //6.0以上执行
            LogUtil.i(TAG, "[onReceivedError: ]  6.0 以上 errorCode = " +
                    error.getErrorCode() + " , description = " + error.getDescription());
        }

    }

    /**
     * 进入相册方法
     */
    @SuppressLint("CheckResult")
    private void intoAlbum() {
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) { // Always true pre-M
                        Matisse.from(this)
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(3)
                                .capture(true)
                                .captureStrategy(new CaptureStrategy(true, AppUtils.getAppPackageName() + ".fileprovider"))
                                .imageEngine(new GlideEngine())
                                .showPreview(true)
                                .theme(com.zhihu.matisse.R.style.Matisse_Zhihu)
                                .forResult(REQUEST_CODE_CHOOSE);
                    } else {
                    }
                });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                List<Uri> urlList = Matisse.obtainResult(data);
                if (urlList.size() > 0) {
                    LogUtil.d(TAG, "[PATH] = " + urlList.get(0).getPath());
                }
                Uri[] array = urlList.toArray(new Uri[0]);
                mFilePathCallBack.onReceiveValue(array);

            }
        } else if (resultCode == RESULT_CANCELED) {
            mFilePathCallBack.onReceiveValue(null);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        mWebView.setVisibility(View.GONE);
        mWebView.clearHistory();
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
        super.onDestroy();
    }


    //==============================================================

    /**
     * 图片旋转
     *
     * @param tmpBitmap tmpBitmap
     * @param degrees   degrees
     * @return
     */
    public static Bitmap rotateToDegrees(Bitmap tmpBitmap, float degrees) {
        Matrix matrix = new Matrix();
        matrix.reset();
        matrix.setRotate(degrees);
        return tmpBitmap =
                Bitmap.createBitmap(tmpBitmap, 0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight(), matrix,
                        true);
    }

    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation =
                    exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
}



    /*@Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                List<Uri> urlList = Matisse.obtainResult(data);
                List<String> urlStringPath = Matisse.obtainPathResult(data);

                if(urlStringPath.size()>0){
                    String path = urlStringPath.get(0);
                    int re = readPictureDegree(path);
                    LogUtil.d(TAG, "[===real PATH] = " + path + ",==方向：" + re);
                }

                List<Uri> newUrlList = new ArrayList<>();
                for (int i = 0;i<urlList.size();i++) {

                    Uri indexUrl = urlList.get(i);
                    String indexPath = urlStringPath.get(i);

                    int degree = readPictureDegree(indexPath);
                    if(degree!=0){
                        try {
                            Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(indexUrl));
                            rotateToDegrees(bitmap,degree);
                            Uri newUri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(),bitmap,null,null));
                            newUrlList.add(newUri);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }else{
                        newUrlList.add(indexUrl);
                    }
                }

                Uri[] array = newUrlList.toArray(new Uri[0]);
                mFilePathCallBack.onReceiveValue(array);

            }
        } else if (resultCode == RESULT_CANCELED) {
            mFilePathCallBack.onReceiveValue(null);
        }
    }*/


